package com.sky.aspect;

import cn.hutool.core.util.ArrayUtil;
import com.sky.anno.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @Author:篍
 * @Date: 2025/08/15 22:28
 * @Description:
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Before("@annotation(com.sky.anno.AutoFill)")
    public void autoFill(JoinPoint joinPoint) throws Exception {
        log.warn("开始进行数据填充");
        Object[] args = joinPoint.getArgs();
        if (ArrayUtil.isEmpty( args)){
            return;
        }
        //获取实体参数
        Object pojo = args[0];
        //反射获取方法上的AutoFill注解
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = methodSignature.getMethod().getAnnotation(AutoFill.class);
        if (Objects.isNull(autoFill)) {
            return;
        }
        Long empId= BaseContext.getCurrentId();
        log.info("当前用户id为{}",empId);
        LocalDateTime now = LocalDateTime.now();
        //获取注解中定义的操作类型,增加、修改
        OperationType value = autoFill.value();
        Class<?> pojoClass = pojo.getClass();
        if (value == OperationType.INSERT){
            pojoClass.getMethod("setUpdateTime", LocalDateTime.class).invoke(pojo, now);
            pojoClass.getMethod("setUpdateUser", Long.class).invoke(pojo, empId);
            pojoClass.getMethod("setCreateTime", LocalDateTime.class).invoke(pojo, now);
            pojoClass.getMethod("setCreateUser", Long.class).invoke(pojo, empId);
        }else if (value == OperationType.UPDATE){
            pojoClass.getMethod("setUpdateTime", LocalDateTime.class).invoke(pojo, now);
            pojoClass.getMethod("setUpdateUser", Long.class).invoke(pojo, empId);
        }
    }
}
